package com.ithao.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ithao.dao.RoleDao;
import com.ithao.dao.UserDao;
import com.ithao.entity.PageResult;
import com.ithao.entity.QueryPageBean;
import com.ithao.pojo.Permission;
import com.ithao.pojo.Role;
import com.ithao.service.RoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author : ZhangHao
 * @version :1.0
 * @date :Created in 2020/4/2
 * @description :
 */
@Service
@Slf4j
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;

    @Override
    public List<Role> findAll() {
        return roleDao.findAll();
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        //开启分页插件
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        //查询数据库
        Page<Role> page = roleDao.findPage(queryPageBean.getQueryParams());
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    @Transactional
    public void add(Role role, Integer[] permissionIds) {
        log.info("[角色-添加]data:{},permissionIds:{}", role, permissionIds);
        //插入基本数据
        roleDao.insert(role);
        //插入角色和权限的中间表
        if (permissionIds.length > 0) {
            for (Integer permissionId : permissionIds) {
                roleDao.insertRoleAndPermissionId(role.getId(), permissionId);
            }
        }
    }

    @Override
    public Role findById(Integer id) {
        return roleDao.findById(id);
    }

    //根据角色Id查询角色的所有权限
    @Override
    public List<Permission> findPermissionByRole(Integer id) {
        return roleDao.selectPermissionByRoleId(id);
    }

    @Override
    @Transactional
    public void update(Role role, Integer[] permissionIds) {
        //更新角色列表
        roleDao.update(role);
        //2、更新关联关系
        //2.1、删除原有关系
        roleDao.deleteRoleAndPermissionByRoleId(role.getId());


        //2.2 插入新的关系
        for (Integer permissionId : permissionIds) {
            roleDao.insertRoleAndPermissionId(role.getId(), permissionId);

        }

    }

    @Override
    @Transactional
    public void delete(Integer id) {
        //删除用户角色中间表
        roleDao.deleteRoleAndUserByRoleId(id);
        //删除角色权限中间表
        roleDao.deleteRoleAndPermissionByRoleId(id);
        //删除角色
        roleDao.delete(id);
    }
}
